package com.bing.test;

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * Created by kaibb on 15-9-8.
 */
public class HelloXML {

    @Test
    public void helloXml() throws ParserConfigurationException, IOException, SAXException {
        Resource resource = new ClassPathResource("conf/test.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(resource.getInputStream());
        NodeList users = document.getChildNodes();

        for (int i = 0; i < users.getLength(); i++) {
            Node user = users.item(i);
            NodeList userInfo = user.getChildNodes();

            for (int j = 0; j < userInfo.getLength(); j++) {
                Node node = userInfo.item(j);
                NodeList userMeta = node.getChildNodes();

                for (int k = 0; k < userMeta.getLength(); k++) {
                    if (userMeta.item(k).getNodeName() != "#text")
                        System.out.println(userMeta.item(k).getNodeName()
                                + ":" + userMeta.item(k).getTextContent());
                }

                System.out.println();
            }
        }
    }
}
